package com.bite.springbootmybatis.mapper;

import com.bite.springbootmybatis.model.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserInfoMapper {
    @ResultMap("BaseMap")
    @Select("select * from userinfo")
    List<UserInfo> queryUserInfos();

    // 有时候会加 为了防止由于版本不同而发生的错误
    @Select("select * from userinfo where id = #{id1}")
    UserInfo queryUserInfo(@Param("id1") Integer id);

    @Select("select * from userinfo where id = #{value}")
    UserInfo queryUserInfo2(Integer id);

    @Select("select * from userinfo where id = #{id1} and username = #{name}")
    UserInfo queryUserInfoByIdAndName(@Param("id1") Integer id1, @Param("name") String username);

    @Insert("insert into userinfo (username, `password`, age, gender, phone) " +
            "values(#{username}, #{password}, #{age}, #{gender}, #{phone})")
    Integer insert(UserInfo userInfo);

    // @Options 可以获取添加的id
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into userinfo (username, `password`, age, gender, phone) " +
            "values(#{userinfo.username}, #{userinfo.password}," +
            " #{userinfo.age}, #{userinfo.gender}, #{userinfo.phone})")
    Integer insert2(@Param("userinfo") UserInfo userInfo);

    @Update("update userinfo set password = #{password} where id = #{id}")
    Integer update(UserInfo userInfo);

    @Delete("delete from userinfo where id = #{id}")
    Integer delete(Integer id);

    // 查询
    // 1. 在 sql 中采用 as
    @Select("select id, username, password, age, gender, phone," +
            " delete_flag as deleteFlag, create_time as createTime," +
            " update_time as updateTime from userinfo")
    List<UserInfo> queryUserInfos2();
    // 2. 采用 @Results
    // 考虑到可能有多出修改 所以给 @Results 添加 id
    @Results(id = "BaseMap", value = {
            @Result(column = "delete_flag", property = "deleteFlag"),
            @Result(column = "update_time", property = "updateTime"),
            @Result(column = "create_time", property = "createTime"),
    })
    @Select("select * from userinfo")
    List<UserInfo> queryUserInfos3();

    // 3. 采用配置属性
    @Select("select * from userinfo")
    List<UserInfo> queryUserInfos4();


    // 采用注解方式动态创建（不推荐） 需要包裹 <script></script>
    @Select("<script>" +
            "insert into userinfo " +
            "(username, password, " +
            "<if test='age != null'> age, </if> " +
            "gender) " +
            "values " +
            "(#{username}, #{password}, " +
            "<if test='age != null'> #{age}, </if> " +
            "#{gender})" +
            "</script>")
    Integer insertUserInfoCondition(UserInfo userInfo);
}
